import datetime
import os

from django.conf import settings
from django.core.files import storage
from django.db import models
from django.template.defaultfilters import filesizeformat
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User
from django.core.files import File

from pypsqueak.settings import MEDIA_ROOT, MEDIA_URL


class Artifact(models.Model):
	""" A simple model to store uploaded files/artifacts """
	title = models.CharField(max_length=255, default="")
	created = models.DateTimeField( default=datetime.datetime.now, editable=False )
	updated = models.DateTimeField( default=datetime.datetime.now, editable=False )

	def get_artifact_path( instance, filename ):
		""" Create a fairly unique path based off of current date/time """
		return  'user_uploads/%s/%s' % (
			datetime.datetime.now().isoformat('.').replace(':','.').replace('-','.'),
			filename )
	file = models.FileField( upload_to=get_artifact_path )


	def save( self ):
		""" Set empty title field to filename """

		#Need to hit save event 2x, as we need to save the file before we know its filename here.
		# Not incredibly smart move on my half, but it's a small hit till I figure it out at a later date.
		super(Artifact, self).save(False, False)

		if( "" == self.title and self.file != None):
			(path, sep, self.title )= self.file.name.rpartition("/")
			super(Artifact, self).save(False, False)



	def __unicode__(self):
		return self.title


	def get_absolute_url(self):
		return self.file.url


	def get_mime_url(self):
		""" Returns the url for the file's mime type """
		ext = self.file.path[-3:]
		if not ext in (
			'.gz','avi','doc','exe','gif','jpg','lxs','mov','mp3',
			'mp4','ocx','pdf','png','ppt','ptx','rtf','tar','txt',
			'wav','xls','zip'
			):
			return MEDIA_URL + "images/mime/other.png"

		else:
			return MEDIA_URL + "images/mime/" + ext + ".png"


	class Admin:
		pass


	class Meta:
		get_latest_by = "updated"
		ordering = [ "title" ]
